<!--
 * @description: 信息 实时数据
 * @author: cuicui
 * @Date: 2023-11-23 11:53:14
 * @LastEditTime: 2023-11-23 14:22:39
 * @LastEditors: cuicui
-->
<template>
  <business-layout title='实时数据' custom-title>
    <template slot='header'>
      <div class='table-tab'>
        <a-tabs v-model='activeKey' :type='conputedEditPermission ? "editable-card" : "card"' @edit='handleEditTab'>
          <a-tab-pane v-for='item in tabs' :key='item.id'>
            <span slot='tab'>
              <a-icon type='edit' v-if='conputedEditPermission' class='edit-tab-color'
                      @click.stop='handleEditTab(item.id, "edit")' />
              {{ item.pageName }}
            </span>
          </a-tab-pane>
        </a-tabs>
      </div>

      <div class='table-operator' style='height: 10px'>
        <a-row style='height: 40px;'>
          <a-form style='height: 40px;' :form='form' layout='inline' @submit='handleQueryData'>
            <a-col :span='4' style='height: 40px;'>
              <a-form-item>
                <a-input v-decorator="['pointName']" allowClear placeholder='请输入点位名称' />
              </a-form-item>
            </a-col>
            <a-col :span='6' style='height: 40px;margin-left: 10px'>
              <a-form-item>
                <a-button type='primary' html-type='submit'>
                  <a-icon type='search' />
                  查询
                </a-button>
                <a-button html-type='reset' style='margin-left: 10px;' @click='handleResetData'>
                  重置
                </a-button>
              </a-form-item>
            </a-col>
            <a-col :span='13' style='height: 40px;margin-left: 10px'>
              <a-button type='primary' style='float: right' v-if='tabs && tabs.length && conputedEditPermission'
                        icon='plus' @click='handleAdd'>新增点位
              </a-button>
              <a-dropdown v-if='selectedRowKeys.length > 0 && conputedEditPermission'
                          style='float: right;margin-right: 10px'>
                <a-menu slot='overlay'>
                  <a-menu-item key='1' @click='handlebulkDelete'>
                    <a-icon type='delete' />
                    删除
                  </a-menu-item>
                </a-menu>
                <a-button style='margin-left: 8px'>
                  批量操作
                  <a-icon type='down' />
                </a-button>
              </a-dropdown>
            </a-col>
          </a-form>
        </a-row>
      </div>
    </template>
    <!--    table-->
    <div style='padding-bottom: 16px' ref='alert-container'>
      <a-alert :showIcon='true'>
        <template slot='message'>
          <span style='margin-right: 12px'>已选择: <a style='font-weight: 600'>{{ selectedRowKeys.length }}</a></span>
        </template>
      </a-alert>
    </div>

    <a-table
      ref='table'
      size='default'
      rowKey='id'
      :alert='true'
      :columns='columns'
      :dataSource='filterTableData  ?  filterTableData : tableData'
      :rowSelection='rowSelection'
    >
      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='description' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>

      <span slot='action' slot-scope='text, record'>
        <template>
          <a @click='handleEdit(record)'>配置</a>
          <a-divider type='vertical' />
          <a @click='handleSub(record)'>订阅报警</a>
        </template>
      </span>
    </a-table>

    <create-point
      :moduleId='moduleId'
      ref='createModal'
      :visible='visible'
      :loading='confirmLoading'
      :model='{}'
      @up-loading='(bol)=> confirmLoading = bol'
      @cancel='handleCancel'
      @ok='handleOk'
    />

    <create-tab
      :title='"页面"'
      ref='createRealTimeModal'
      :visible='realTimeCreatevisible'
      :loading='realTimeCreateConfirmLoading'
      :model='realTimeModel'
      @cancel='handlRealTimeeCancel'
      @ok='handleRealTimeOk' />
  </business-layout>
</template>

<script>
import realTimePageApi, {
  findAllPagesByModuleId,
  create,
  remove,
  update,
  assignPointToPage,
  deletePointOfPage
} from '@/api/realTimeData'
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { mapState } from 'vuex'
import CreateTab from '@/business-components/create-tab/index.vue'
import CreatePoint from '@/business-components/create-point'
import { WS_SENDDATA, WS_DATA } from '@/store/mutation-types'

const columns = [
  {
    title: '编号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '系统ID',
    dataIndex: 'systemId'
  },
  {
    title: '系统名称',
    dataIndex: 'systemName'
  },
  {
    title: '设备ID',
    dataIndex: 'deviceId'
  },
  {
    title: '设备名称',
    dataIndex: 'deviceName'
  },
  {
    title: '点位ID',
    dataIndex: 'pointId'
  },
  {
    title: '点位名称',
    dataIndex: 'pointName'
  },
  // {
  //   title: '时间',
  //   dataIndex: 'updatedTime'
  // },
  {
    title: '数据',
    dataIndex: 'value'
  },
  {
    title: '单位',
    dataIndex: 'pointUnit'
  }
]

// 模块id 不同模块id不同
const moduleId = '04'
const editMark = 'xinxibianji'
export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreatePoint,
    CreateTab
  },
  data() {
    this.moduleId = moduleId
    this.columns = columns
    return {
      tabs: [],
      form: this.$form.createForm(this),
      activeKey: '',
      // create model
      visible: false,
      realTimeCreatevisible: false,
      confirmLoading: false,
      realTimeCreateConfirmLoading: false,
      mdl: null,
      realTimeModel: null,
      // 查询参数
      queryParam: {},
      filterTableData: null,
      Socket: null,
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {},
  computed: {
    ...mapState({
      tableData: state => state.ws[WS_DATA],
      permissionList: state => [...new Set(state.user.info.permissionList.filter(item => item.type === 'I').map(item => item.permissionCode))],
      userType: state => state.user.info.userType
    }),
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    },
    conputedEditPermission() {
      if (this.userType === '1') {
        return true
      }
      if (this.permissionList.includes(editMark)) {
        return true
      }
      return false
    }
  },
  watch: {
    activeKey(val) {
      this.$store.dispatch(WS_SENDDATA, val)
      this.handleResetData()
    }
  },
  created() {
    this.findAllPagesByModuleId()
  },
  methods: {
    handleResetData() {
      this.queryParam = {}
      this.form.resetFields()
      this.filterTableData = null
    },
    handleQueryData(e) {
      e.preventDefault()
      const form = this.form
      const that = this
      form.validateFields((error, values) => {
        const { pointName } = values
        if (!pointName) {
          that.filterTableData = that.tableData
          return
        }
        that.filterTableData = that.tableData.filter(item => item.pointName.indexOf(pointName) !== -1)
      })
    },
    handlebulkDelete() {
      const that = this
      this.$confirm({
        title: '警告',
        content: '当前操作不可逆、是否继续？',
        onOk() {
          that.deletePointOfPage()
        }
      })
    },
    async deletePointOfPage() {
      const result = await deletePointOfPage({
        id: this.selectedRows.map(item => item.id),
        pageId: this.activeKey
      })
      if (result) {
        this.onSelectChange([], [])
        this.$message.success('删除成功!')
      }
    },
    // 查询当前页面tab
    async findAllPagesByModuleId() {
      this.tabs = await findAllPagesByModuleId({ moduleId })
      if (this.tabs && this.tabs.length > 0 && !this.activeKey) {
        this.activeKey = this.tabs[0].id
        this.$store.dispatch(WS_SENDDATA, this.activeKey)
      }
    },
    removeTab(id) {
      const that = this
      this.$confirm({
        title: '警告',
        content: '当前操作不可逆、是否继续？',
        async onOk() {
          const result = await remove({ id })
          if (result) {
            that.findAllPagesByModuleId()
            // 删除tab为当前选中tab的话重置到第一个选项
            if (that.activeKey === id) {
              that.activeKey = ''
            }
            that.$message.success('更新成功！')
            that.handlRealTimeeCancel()
          }
        }
      })
    },
    handleEditTab(tagetKey, action) {
      if (action === 'add') {
        this.realTimeCreatevisible = true
        this.$refs.table.refresh()
      }
      if (action === 'remove') {
        this.removeTab(tagetKey)
        this.$refs.table.refresh()
      }
      if (action === 'edit') {
        this.realTimeCreatevisible = true
        const tabItem = this.tabs.find(item => item.id === tagetKey)
        this.realTimeModel = {
          ...tabItem,
          pageName: tabItem.pageName
        }
        this.$refs.table.refresh()
      }
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleRealTimeOk() {
      const that = this
      const form = this.$refs.createRealTimeModal.form
      form.validateFields(async (errs, values) => {
        if (errs) {
          return
        }
        const { pageName, id } = values
        if (!id) {
          const reulst = await create({
            moduleId,
            pageName: pageName
          })
          if (reulst) {
            that.findAllPagesByModuleId()
            that.$message.success('创建成功！')
            that.handlRealTimeeCancel()
          }
          return
        }
        const reulst = await update({
          moduleId,
          id,
          pageName: pageName
        })
        if (reulst) {
          that.findAllPagesByModuleId()
          that.$message.success('创建成功！')
          that.handlRealTimeeCancel()
        }
      })
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields(async (errors, values) => {
        if (!errors) {
          try {
            const { pointDicList } = values
            if (!pointDicList || !pointDicList.length) {
              this.$message.error('请选择相关信息！')
              this.confirmLoading = false
              return
            }
            const { activeKey, $message } = this
            const result = await assignPointToPage(pointDicList.map(pointDicId => {
              return {
                pageId: activeKey,
                pointId: pointDicId
              }
            }))
            if (result) {
              $message.success('创建成功')
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()
            }
          } finally {
            this.confirmLoading = false
          }
        } else {
          this.$message.error('请选择！')
          this.confirmLoading = false
        }
      })
    },
    handlRealTimeeCancel() {
      const form = this.$refs.createRealTimeModal.form
      form.resetFields() // 清理表单数据（可不做）

      this.realTimeCreatevisible = false
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.success(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style lang='less' scoped>
.table-tab {

}

.ant-menu-item-selected {
  background-color: red !important;
}
</style>